/**
 * author: redd
 * create_time: 2017/12/27 10:20
 * description:
 */
 



import React, {Component} from 'react'
import PropTypes from 'prop-types'

const buttonStyle = {
  margin: '10px'
}

export default class Counter extends Component {

  constructor(props) {
    super(props)

    this.state = {
      count: props.initValue
    }

    this.onClickDecrementButton = this.onClickDecrementButton.bind(this)
    this.onClickIncrementButton = this.onClickIncrementButton.bind(this)
  }

  onClickIncrementButton() {
    this.updateCount(true)
  }

  onClickDecrementButton() {
    this.updateCount(false)
  }

  updateCount(isIncrement) {
    const previousValue = this.state.count
    const newValue = isIncrement ? previousValue + 1 : previousValue - 1

    this.setState({
      count: newValue
    })

    this.props.onUpdate(newValue, previousValue)
  }


  render() {
    const {caption} = this.state
    return (
      <div>
        <button style={buttonStyle} onClick={this.onClickIncrementButton}>+</button>
        <button style={buttonStyle} onClick={this.onClickDecrementButton}>-</button>
        <span>{caption} count: {this.state.count} </span>
      </div>
    )
  }
}


Counter.propTypes = {
  caption: PropTypes.string.isRequired,
  initValue: PropTypes.number,
  onUpdate: PropTypes.func
}

Counter.defaultProps = {
  initValue: 0,
  onUpdate: f => f
}